function Gui_icu24gp()
%GUI_ICU24G	compute GP analysis for the first 24 hours after ICU admission
%	Gui_icu24gp()
%
%
%	Inputs:
%
%
%
%	Outputs:
%
%
%   See also demogpsimilarity nd_icu

%	References: N/A
%

%	Copyright 2013 MAF Pimentel
%	This program is free software: you can redistribute it and/or modify
%	it under the terms of the GNU General Public License as published by
%	the Free Software Foundation, either version 3 of the License, or
%	(at your option) any later version.
%
%	This program is distributed in the hope that it will be useful,
%	but WITHOUT ANY WARRANTY; without even the implied warranty of
%	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%	GNU General Public License for more details.
%
%	You should have received a copy of the GNU General Public License
%	along with this program.  If not, see <http://www.gnu.org/licenses/>.


%	$Author: MAF Pimentel$
%	$Revision: 1.0.0.0$
%	$Date: 11-Jun-2013 14:55:44$
%	Contact: marco.and.pimentel@gmail.com
%	Originally written on: PCWIN64

%% Load patient structure and define ranges for the different variables
%% under investigation
addpath('utils/');
load '../data/ptstruct2.mat';

LIMS = [20 350; ...             % HR
    0 300; ...                  % Pulse Pressure
    0 50; ...                   % Lactate
    0 1000; ...                 % Urine Output
    30 300];                    % Mean Arterial Pressure

PLOTLIMS = [40 250 1; ...       % HR
    0 200 1; ...                % Pulse Pressure (PP)
    0 50 1; ...                 % Lactate (LA)
    0 300 1; ...                % Urine Output (UO)
    40 250 1];                  % Mean Arterial Pressure (MAP)

LABELS = {'Heart Rate (bpm)','Pulse Pressure (mmHg)', ...
    'Acid Lactic','Urine Output (cc/kg/hr)','Mean Arterial Pressure (mmHg)'};

clc; close all;

%% Get ids for different classes of patients

if exist('../outputs/dynamics/datastruct2.mat')
    load('../outputs/dynamics/datastruct2.mat');
else
    [datastruct, ndata] = get_ptclassids(ptstruct,'mort28d');
    save('../outputs/dynamics/datastruct2.mat','datastruct','ndata');
end

if isempty(datastruct)
    fprintf('\nCheck group of patients\n');
    return;
end

%% Cleaning data
%  for urine output and lactate
% alldata{5} = [];
% for pt = 1 : length(datastruct)
%     for i = 1 : 5
%         if ~isempty(datastruct{pt}.data{i})
%             alldata{i} = [alldata{i}; datastruct{pt}.data{i}(:,2)];
%         end
%     end
% end
%
% disp('');
% for i = 1 : 5
% figure;
% hist(alldata{i},0:1:6000);
% end

%% Get ids of patients to use in the analysis and compute summary statistics
% Select which variables to analyse
variables = [1 2 5];

if length(variables) == 3
    ids = intersect(ndata{variables(1)},ndata{variables(2)});
    ids = intersect(ids,ndata{variables(3)});
elseif length(variables) == 4
    ids = intersect(ndata{variables(1)},ndata{variables(2)});
    ids = intersect(ids,ndata{variables(3)});
    ids = intersect(ids,ndata{variables(4)});
elseif length(variables) == 2
    ids = intersect(ndata{variables(1)},ndata{variables(2)});
end

% Select Patients with more an ICU stay longer than one day
ids1 = ids; ids = []; % ids correspond to the findal IDs of the patients in datastruct
for i = ids1
    if datastruct{i}.los > 1
        ids = [ids i];
    end
end

% Create gpinfo structure
if exist('../outputs/dynamics/infogp.mat')
    load('../outputs/dynamics/infogp.mat');
else
    % gpinfo contains information about whether gp has been performed or
    % not in the specified variable. The organisation is as follows (in columns):
    % 1 - Pt. ID, 2 - ICU ID, 3-7 - data as specified in datastruct
    infogp = zeros(length(datastruct),7);
    for i = 1 : length(datastruct)
        infogp(i,1) = datastruct{i}.ptid;
        infogp(i,2) = datastruct{i}.iid;
    end
    save('../outputs/dynamics/infogp.mat','infogp');
end

% Show stats
showstats(datastruct,ids1,ids)

%% Run GPR and extract valid information
% Perform Gaussian Process regression for all patients
run('../Toolboxes/GP_v3/startup.m'); % Add directories of GP_v3 toolbox to path
xtest = (0:1/48:1)'; % xtest, test input variable

% initialise progress bar
%progressbar('Running GP regression...');
DOPLOT = 0;

tic;
for c = 1 : length(ids)
    for v = 1 : length(variables)
        var_ = variables(v); % Pick the parameter to analyse
        i = ids(c);
        % check if the GP has been performed for this patient
        ptid = datastruct{i}.ptid; iid = datastruct{i}.iid;
        ind = find(infogp(:,1) == ptid & infogp(:,2) == iid);
        if infogp(ind,var_+2) ~= 1  % if GP hasn't been performed yet
            % Get first 24 hours of data... xtrain is converted to days
            [xtrain,ytrain] = getfirstdaydata(datastruct,i,var_,LIMS(var_,:));
            
            % Apply GP
            [nlml,hyp_prior,hyp_post,ytest] = Run_icu24gp(xtrain,ytrain,xtest,DOPLOT);
            
            % complete data structure with results from the model
            datastruct{i}.gp{var_}.xtrain = xtrain; datastruct{i}.gp{var_}.ytrain = ytrain;
            datastruct{i}.gp{var_}.xtest = xtest; datastruct{i}.gp{var_}.ytest = ytest;
            datastruct{i}.gp{var_}.hyp_prior = hyp_prior;
            datastruct{i}.gp{var_}.hyp_post = hyp_post;
            datastruct{i}.gp{var_}.nlml = nlml;
            
            % Update information on infogp record...
            infogp(ind,var_+2) = .5;
        end
        
        
    end
    
    % SAVE outputs every 10 subjects...
    if rem(c,10) == 0
        % Build string with variable inputs:
        strvariable = '';
        for vs = variables
            strvariable = sprintf('%sv%d',strvariable,vs);
        end
        % save output with data created so far
        filename = sprintf('../outputs/dynamics/datastruct_%s_it%d.mat',strvariable,c);
        save(filename,'datastruct','ids');
        % Update information on infogp record... and SAVE it
        infogp(infogp(:,var_+2) == 0.5,var_+2) = 1;
        save('../outputs/dynamics/infogp.mat','infogp');
    end
    
    % Update progress bar
    %progressbar(c/length(ids));
    fprintf('\n\n --- Complete %.1f ---\n\n',c/length(ids));
    toc;
    disp('');
end

% Don't forget to SAVE final results after loop...
filename = sprintf('../output/dynamics/datastruct_%s.mat','final');
save(filename,'datastruct','ids');
infogp(infogp(:,var_+2) == 0.5,var_+2) = 1;
save('../outputs/dynamics/infogp.mat','infogp');
